package com.wichell.framework.wechat.util;

import java.text.MessageFormat;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.fasterxml.jackson.core.type.TypeReference;
import com.wichell.framework.util.HttpRequestUtil;
import com.wichell.framework.util.JacksonUtil;
import com.wichell.framework.wechat.bo.response.BaseWechatResponse;
import com.wichell.framework.wechat.exception.WechatRequestException;

public final class WechatUtils {

	private static final Logger _logger = Logger.getLogger(WechatUtils.class);

	/**   
	 * @Title: request   
	 * @Description: 微信请求通用处理
	 * @param: @param requestUrl
	 * @param: @return
	 * @param: @throws WechatRequestException      
	 * @return: T      
	 * @throws   
	 */
	public static <T extends BaseWechatResponse> T request(String requestUrl) throws WechatRequestException {
		try {
			String response = HttpRequestUtil.doGet(requestUrl);

			if (_logger.isDebugEnabled()) {
				_logger.debug(MessageFormat.format("请求url:{0}, 响应:{1}", requestUrl, response));
			}

			T result = JacksonUtil.json2Obj(response, new TypeReference<T>() {
			});
			return processResponse(result);
		} catch (Exception e) {
			e.printStackTrace();
			_logger.error(MessageFormat.format("请求url:{0},  异常:{1}", requestUrl, e.getMessage()));
			throw new WechatRequestException(MessageFormat.format("请求异常:{0}", e.getMessage()));
		}
	}

	/**   
	 * @Title: request   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param requestUrl
	 * @param: @param postData
	 * @param: @return
	 * @param: @throws WechatRequestException      
	 * @return: T      
	 * @throws   
	 */
	public static <T extends BaseWechatResponse> T request(String requestUrl, String postData)
			throws WechatRequestException {
		try {
			String response = HttpRequestUtil.doJson(requestUrl, postData);
			if (_logger.isDebugEnabled()) {
				_logger.debug(MessageFormat.format("请求url:{0}, 参数:{1}, 响应:{2}", requestUrl, postData, response));
			}
			T result = JacksonUtil.json2Obj(response, new TypeReference<T>() {
			});
			return processResponse(result);
		} catch (Exception e) {
			e.printStackTrace();
			_logger.error(MessageFormat.format("请求url:{0}, 参数:{1}, 异常:{2}", requestUrl, postData, e.getMessage()));
			throw new WechatRequestException(MessageFormat.format("请求异常:{0}", e.getMessage()));
		}
	}

	private static <T extends BaseWechatResponse> T processResponse(T resp) throws WechatRequestException {
		if (StringUtils.isBlank(resp.getErrorCode())) {
			return (T) resp;
		} else {
			throw new WechatRequestException(resp.getErrMsg());
		}
	}
}
